//
//  DeviceVc.m
//  ainkjj
//
//  Created by zhiyiLiu on 2020/3/12.
//  Copyright © 2020 zhiyiLiu. All rights reserved.


#import "DeviceVc.h"

#import "DeviceInfoVc.h"

#import "DeviceMusicVc.h"
#import "DeviceGuanaiVc.h"
#import "DeviceYaobaiVc.h"

#import "Device_mqtt_publish_model.h"
#import "Device_mqtt_sub_model.h"

#import "App_getMusicList.h"

#import "Ank_musicList_view.h"
#import "Shebei_offline_popView.h"
#import "MQTTLog.h"

#import <HWPanModal/HWPanModal.h>
#import "Music_page_list_vc.h"
#import "GetMusicReq.h"
#import "GetMusic_category_list.h"

@interface DeviceVc ()<MQTTSessionManagerDelegate>
@property (nonatomic, strong)NSMutableArray *classNamesArr;
@property (nonatomic, copy) NSString *ainankang_app_topic;
@property (nonatomic, copy) NSString *ainankang_dev_topic;
@property (nonatomic, strong)DeviceMusicVc *musicVc;
@property (nonatomic, strong)DeviceYaobaiVc *yaobaiVc;
@property (nonatomic, strong)DeviceGuanaiVc *guanaiVc;
@property (nonatomic, copy) NSString *login_report_MAC;
@property (nonatomic, copy) NSString *login_report_dev_type;

@property (nonatomic, assign)BOOL has_send_music_list;
@property (nonatomic, strong)NSTimer *check_handshake_timer;
@property (nonatomic, strong)Music_page_list_vc *music_list_vc;
@property (nonatomic, strong)NSMutableDictionary *music_database;//只为设备回调当前播放的url时，我能找到歌曲信息并显示

@end

@implementation DeviceVc

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];


}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [MBProgressHUD hideHUD];

    [self.check_handshake_timer invalidate];
    self.check_handshake_timer = nil;
    
}
- (void)dealloc{
    
    
    if (self.deviceInfo.data.is_virtual == NO) {// 虚拟设备后面的不再执行了
        return;
    }
    [self.sessionManager disconnectWithDisconnectHandler:^(NSError *error) {
        if (error) {
            DLog(@"%@",error);
        }else{
            [self.sessionManager requiresTearDown];
        }
    }];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"current_song_change_to_Device_vc" object:nil];

    DLog(@"(づ￣3￣)づ╭❤～庆祝");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.music_database = NSMutableDictionary.new;
    [self cache_music];

    [self req_device_info];

    if (!self.entity.device_name){
        self.title = self.entity.name;
    }else{
        self.title = self.entity.device_name;
    }
    
    UIBarButtonItem *rItem = [[UIBarButtonItem alloc] initWithTitle:@"设备详情" style:UIBarButtonItemStylePlain target:self action:@selector(rItemAction)];
    self.navigationItem.rightBarButtonItem = rItem;    
    
    self.view.backgroundColor = UIColor.groupTableViewBackgroundColor;
    self.menuView.backgroundColor = UIColor.whiteColor;
    self.scrollEnable = NO;
    
    
    if ([Anktool strIsBlank:self.entity.device_id]) {
        DLog(@"发生错误，无设备id");
    }else{
        
        self.ainankang_app_topic = [@"ainankang_app/" stringByAppendingString:self.entity.device_id];
        self.ainankang_dev_topic = [@"ainankang_dev/" stringByAppendingString:self.entity.device_id];
        
    }
    

    if (self.entity.is_virtual == NO) {// 虚拟设备后面的不再执行了
        // 移除扫码控制器
        NSMutableArray *sub_vc = self.navigationController.viewControllers.mutableCopy;
        if (sub_vc.count == 3) {
            [sub_vc removeObjectAtIndex:1];
            self.navigationController.viewControllers = sub_vc;
        }
        
        
        self.musicVc.light_switch.userInteractionEnabled = self.yaobaiVc.light_switch.userInteractionEnabled = NO;

        return;
    }else{
        self.musicVc.light_switch.userInteractionEnabled = self.yaobaiVc.light_switch.userInteractionEnabled = YES;
    }
    
    [self mqtt_manager];
    
  
}
- (void)setCurrentListData:(GetMusicData *)currentListData{
    
    if (_currentListData == nil) {
        
        //设置播放默认
        self.audio_play_model = @"lists_cycle";
        
        self.audio_execute_status = @"close";
        self.musicVc.play_pause_btn.selected = NO;
        [self.musicVc.play_mode_btn setImage:[UIImage imageNamed:self.audio_play_model] forState:UIControlStateNormal];
    }
    
    _currentListData = currentListData;
    if ([Anktool strIsBlank:currentListData.base_url]) {
        DLog(@"解析出错");
        return;
    }
    
    

    
}
- (void)current_song_change:(NSNotification *)noti{
    NSDictionary *userInfo = noti.userInfo;
    GetMusicList *model = [userInfo objectForKey:@"current_song_change_to_Device_vc"];
    DLog(@"%@", model.title);
    

    
    if (![Anktool strIsBlank:model.file_name]) {
        
        if ([model.url isEqualToString:self.currentSong.url]) {
            NSArray *dataArr = nil;
            if ([self.audio_execute_status isEqualToString:@"open"]) {
                // 当前是在播放音乐的状态，再点击一下是暂停
                dataArr =@[ @{@"reg": @"status", @"value" : @"pause"}];
                
                self.audio_execute_status = @"pause";
                
            }else if ([self.audio_execute_status isEqualToString:@"close"]) {
                
                // 当前是没有在播放音乐的状态，再点击一下是播放第一首歌曲
                dataArr =@[ @{@"reg": @"status", @"value" : @"open"}];
                self.audio_execute_status = @"open";
                
            }else if ([self.audio_execute_status isEqualToString:@"pause"]) {
                // 当前是在播放音乐的，只是音乐处于暂停状态，再点击一下是恢复
                dataArr =@[ @{@"reg": @"status", @"value" : @"recover"}];
                self.audio_execute_status = @"recover";
                
            }else if ([self.audio_execute_status isEqualToString:@"recover"]) {
                // 当前是音乐恢复播放的状态，再点击一下是暂停
                dataArr =@[ @{@"reg": @"status", @"value" : @"pause"}];
                self.audio_execute_status = @"pause";
                
            }
            //                else if ([self.audio_execute_status isEqualToString:@"mute"]){}
            
            [self queryWith_cmd:@"audio" data:dataArr];
            
        }else{
            
            NSMutableArray *dataArr = [NSMutableArray array];
            [dataArr addObject:@{
                @"reg" : @"url" // 当前播放的 音频文件路径/URL地址
                , @"value" : model.url
            }];
            [dataArr addObject:@{
                @"reg" : @"status"
                , @"value" : @"open"
            }];
            
            [self queryWith_cmd:@"audio" data:dataArr];
            
            for (NSString *key in self.music_database.allKeys) {
                GetMusicData *aListData = [self.music_database objectForKey:key];
                for (GetMusicList *aSong in aListData.list) {
                    if ([aSong.url isEqualToString:model.url]) {
                        self.currentListData = aListData;
                        self.currentSong = model;
                        [self list_send:aListData];
                        return;
                    }
                }
            }
        }
    }
    
    
    
    
    
    
}
- (void)req_device_info{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
    
    
    [dict setObject:app_code forKey:@"app_code"];
    [dict setObject:self.entity.device_id forKey:@"device_id"];
    
    
    [PPHTTPRequest req:@"api/App/deviceInfo" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            App_deviceInfo *deviceInfo = [App_deviceInfo mj_objectWithKeyValues:response];
            self.deviceInfo = deviceInfo;
            [self.guanaiVc update_guanai_ui];
        }
        
        else
            //            if ([error_code isEqualToString:@""])
        {
            
            [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
            
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showTipMessageInView:[error localizedDescription]];
        
    }];
}



- (void)rItemAction{
    DeviceInfoVc *vc= [[DeviceInfoVc alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.entity = self.deviceInfo.data;
    vc.blk = ^(NSString *name_new) {
        self.title = name_new;
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (NSMutableArray *)titlesArr{
    if(_titlesArr == nil)
    { _titlesArr = @[@"音乐", @"摇摆", @"关爱"].mutableCopy;
    }
    
    return _titlesArr;
}
- (NSMutableArray *)classNamesArr{
    if(_classNamesArr == nil)
    {_classNamesArr = @[ @"DeviceMusicVc", @"DeviceYaobaiVc", @"DeviceGuanaiVc",].mutableCopy;
    }
    
    return _classNamesArr;
}

#pragma mark - WMPageController DataSource
- (NSInteger)numbersOfChildControllersInPageController:(WMPageController *)pageController {
    return self.titlesArr.count;
}

- (NSString *)pageController:(WMPageController *)pageController titleAtIndex:(NSInteger)index {
    return self.titlesArr[index];
}

- (UIViewController *)pageController:(WMPageController *)pageController viewControllerAtIndex:(NSInteger)index {
    UIViewController *vc = nil;
    switch (index) {
        case 0:
            vc = self.musicVc;
            break;
            
        case 1:
            vc = self.yaobaiVc;
            break;
            
        case 2:
            vc = self.guanaiVc;
            break;
            
        default:
            vc = [QDCommonViewController new];
            break;
    }
    return vc;
}
-(CGRect)pageController:(WMPageController *)pageController preferredFrameForMenuView:(WMMenuView *)menuView{
    CGFloat originY =  CGRectGetMaxY(self.navigationController.navigationBar.frame);

    return  CGRectMake(0,  originY, [UIScreen mainScreen].bounds.size.width, 50);
}
- (CGRect)pageController:(WMPageController *)pageController preferredFrameForContentView:(WMScrollView *)contentView{
    CGFloat originY = CGRectGetMaxY([self pageController:pageController preferredFrameForMenuView:self.menuView]);
//    originY = Lzy_StatusBarAndNavigationBarHeight;
    return  CGRectMake(0, originY, self.view.bounds.size.width,self.view.bounds.size.height - originY);
    
}


#pragma mark - ================== mqtt manager ==================
- (void)mqtt_manager{
    
    if (!self.sessionManager) {
        self.sessionManager = [[MQTTSessionManager alloc] init];
        self.sessionManager.delegate = self;
        [MQTTLog setLogLevel:DDLogLevelWarning];
        
        /**
         host: 服务器地址
         port: 服务器端口
         tls:  是否使用tls协议，mosca是支持tls的，如果使用了要设置成true
         keepalive: 心跳时间，单位秒，每隔固定时间发送心跳包, 心跳间隔不得大于120s
         clean: session是否清除，这个需要注意，如果是false，代表保持登录，如果客户端离线了再次登录就可以接收到离线消息
         auth: 是否使用登录验证
         user: 用户名
         pass: 密码
         willTopic: 订阅遗嘱主题
         willMsg: 自定义的离线消息
         willQos: 接收离线消息的级别
         clientId: 客户端id，需要特别指出的是这个id需要全局唯一，因为服务端是根据这个来区分不同的客户端的，默认情况下一个id登录后，假如有另外的连接以这个id登录，上一个连接会被踢下线, 我使用的设备UUID
         */
        NSString *clientId = [NSString stringWithFormat:@"%@%@", [FCUUID uuidForDevice], AuthSignin_model.sharedInstance.data.user_info.mobile];
        //        [self.sessionManager setSubscriptions:@{@"TopicApp/DeviceId" : @(MQTTQosLevelExactlyOnce)}];
        
        
        
        // 订阅主题    NSDictionary类型，Object 为 QoS，key 为 Topic
        NSMutableDictionary *subTopic = [NSMutableDictionary dictionary];
        [subTopic setObject:@(MQTTQosLevelAtMostOnce) forKey:@"ainankang_dev"];// 公共主题，握手之前，设备发出来的
        if ([Anktool strIsBlank:self.ainankang_dev_topic]) {
            DLog(@"设备id为空");
        }else{
            [subTopic setObject:@(MQTTQosLevelAtMostOnce) forKey:self.ainankang_dev_topic];
        }
        self.sessionManager.subscriptions = subTopic;
        
        MQTTSSLSecurityPolicy *sp = [MQTTSSLSecurityPolicy policyWithPinningMode:MQTTSSLPinningModeNone];
        
        [self.sessionManager connectTo:@"47.97.127.229"
                                  port:1883
                                   tls:false
                             keepalive:60  //心跳间隔不得大于120s
                                 clean:true
                                  auth:true
                                  user:@"ainankang_user01"
                                  pass:@"ainankang@01"
                                  will:NO
                             willTopic:nil
                               willMsg:nil
                               willQos:0
                        willRetainFlag:false
                          withClientId:clientId
                        securityPolicy:sp
                          certificates:nil
                         protocolLevel:MQTTProtocolVersion311
                        connectHandler:^(NSError *error) {
                            
                            if (error) {
                                DLog(@"error:%@", error);
                            }else{
                                [self send_handshake_msg];
                            }
                            
                        }];
        
        
    }else{
        /*
         MQTTSessionManagerStateStarting,
         MQTTSessionManagerStateConnecting,
         MQTTSessionManagerStateError,
         MQTTSessionManagerStateConnected,
         MQTTSessionManagerStateClosing,
         MQTTSessionManagerStateClosed
         */
        if (self.sessionManager.state == MQTTSessionManagerStateConnected) {
            [self query_shebei_local_music_list];

        }else{
            [self.sessionManager connectToLast:^(NSError *error) {
                
                if (error) {
                    DLog(@"error:%@", error);
                }else{
                    [self query_shebei_local_music_list];
                    
                }
            }];
        }
        
        
    }
    
    [self check_handshake];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(current_song_change:) name:@"current_song_change_to_Device_vc" object:nil];
}
#pragma mark - ================== 发 ==================
- (void)setHandshake_yes:(BOOL)handshake_yes{
    if (_handshake_yes == NO && handshake_yes == YES) {
        [self query_shebei_local_music_list];
    }
    _handshake_yes = handshake_yes;
    if (handshake_yes == YES) {
        [MBProgressHUD hideHUD];
    }
}
- (void)send_handshake_msg{
    
//    [MBProgressHUD showActivityMessageInView:@"加载中"];
    NSMutableArray *dataArr = [NSMutableArray array];
    NSString *mac = self.login_report_MAC.length != 0 ? self.login_report_MAC : self.entity.device_mac.length != 0 ? self.entity.device_mac : @"C44F3314ECF5";
    [dataArr addObject:@{@"reg":@"MAC",
                         @"value" : mac
                         }];
    [self queryWith_cmd:@"handshake" data:dataArr];
    
    
    
}

- (void)send_music_list_reg{
    // 请求音乐列表
    
    
    
    GetMusicReq *api =[[GetMusicReq alloc] init];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        // 你可以直接在这里使用 self
        NSLog(@"succeed");
        NSDictionary *response = request.responseJSONObject;
        
        
        
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            MusicCategory *musicCategory = [MusicCategory mj_objectWithKeyValues:request.responseJSONObject];
            
            MusicCategoryData *ac = musicCategory.data.firstObject;
            GetMusic_category_list *req = [[GetMusic_category_list alloc] init_page:@"1" page_size:@"100" category_id:@(ac.ID).stringValue];
            [req startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull rq) {
                NSDictionary *res = rq.responseJSONObject;
                
                NSString *error_code = [NSString stringWithFormat:@"%@", res[@"error_code"]];
                if ([error_code isEqualToString:@"0"]) {
                    GetMusic *model = [GetMusic mj_objectWithKeyValues:res];
                    
                    if (!model.data.list || model.data.list.count == 0) {
                        DLog();
                        return;
                    }else{
                        // 拿到默认音乐列表
                        // 自动定位第一首
                        self.defaultSong = self.currentSong = model.data.list.firstObject;
                        self.currentListData = model.data;
                        [self list_send:model.data];
                    }
                    
                }else{
                    
                    [QMUITips showError:res[@"error_msg"] ];
                }
                
                
            } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                
            }];
        }

      
        
    } failure:^(YTKBaseRequest *request) {
        // 你可以直接在这里使用 self
        NSLog(@"failed");
    }];
    
    
   
    
}

- (void)list_send:(GetMusicData *)currentListData{
    NSMutableArray *valueArr = [NSMutableArray array];
    for (GetMusicList *aSong in currentListData.list) {
        if (![Anktool strIsBlank:aSong.file_name]) {
            
            [valueArr addObject:@{@"url" : aSong.file_name}];
            
        }
    }
    
    //    App_getMusicListMusic_list *song = self.musicList.data.music_list.firstObject;
    NSString *base_url = currentListData.base_url;
    NSArray *dataArr = @[@{@"reg": @"music_list",
                           @"base_url": base_url,
                           @"addr" : @"remote",
                           @"value": valueArr.copy}];
    [self queryWith_cmd:@"audio" data:dataArr];
}

- (void)query_shebei_local_music_list{
    DLog(@"2--------------->询问设备 音乐列表");
    NSArray *dataArr = @[@{@"reg" : @"music_list_get"}// 获取设备的播放列表，以此来判定设备中是否已经有了播放列表，没有播放列表要推给设备，有的话就不用了
                         ];
    [self queryWith_cmd:@"audio" data:dataArr];
    
    // 询问夜灯情况
    [self queryWith_cmd:@"dev" data:@[@{@"reg" : @"lights_sw_get"}
                                      ]];

}
- (void)query_music_info{
    NSArray *dataArr = @[
//                         @{@"reg" : @"audio_get"} // 此方法是本地有音乐列表。音频所有信息查询 不能用这个指令，会触发music_list指令返回陷入死循环
                         @{ @"reg" : @"volume_get"},
                         @{ @"reg" : @"broadcast_pace_get"},
                         @{ @"reg" : @"addr_get"},
                         @{ @"reg" : @"url_get"},
                         @{ @"reg" : @"status_get"},
                         @{ @"reg" : @"mode_get"},
//                         @{ @"reg" : @""},
//                         @{ @"reg" : @""},

                         ];
    [self queryWith_cmd:@"audio" data:dataArr];
}
- (void)query_page_info{
    NSArray *dataArr = @[@{
                             @"reg": @"device_get"   //     -------------->设备所有信息 获取
                             }
                         ];
    [self queryWith_cmd:@"dev" data:dataArr];
}

- (void)queryWith_cmd:(NSString *)cmd data:(NSArray *)dataArr{
    if (self.deviceInfo.data.is_virtual == NO) {
        return;
    }
    Device_mqtt_publish_model *pub_msg = [Device_mqtt_publish_model new];

    pub_msg.dev_id = self.deviceInfo.data.device_id;
    NSString *type = self.login_report_dev_type.length != 0 ? self.login_report_dev_type : self.entity.device_type.length != 0 ? self.entity.device_type : self.deviceInfo.data.device_type.length != 0 ? self.deviceInfo.data.device_type : self.deviceInfo.data.model.length != 0 ? self.deviceInfo.data.model : @"YA-HBB-19A";
    pub_msg.dev_type = type;//@"YA-HBB-19A" self.deviceInfo.data.device_type
    pub_msg.index = @(++AuthSignin_model.sharedInstance.msgIndex).stringValue;
    
    pub_msg.cmd = cmd;
    
    pub_msg.data = dataArr.copy;
    
    NSString *pub_msg_str = [[pub_msg mj_JSONString] stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    DLog(@"%@", pub_msg_str);
    // {"cmd":"handshake","data":[{"reg":"MAC","value":"C44F3314ECF5"}],"dev_id":"IF-YA-HBB-19A-C44F3314ECF5-6300","dev_type":"YA-HBB-19A","index":0}
    [self.sessionManager
     sendData:[pub_msg_str dataUsingEncoding:NSUTF8StringEncoding] //要发送的消息体
     topic:self.ainankang_app_topic //要往哪个topic发送消息
     qos:0 //消息级别
     retain:false];
}

#pragma mark - ================== 收 ==================

- (void)sessionManager:(MQTTSessionManager *)sessionManager
     didReceiveMessage:(NSData *)data
               onTopic:(NSString *)topic
              retained:(BOOL)retained{
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        
        Device_mqtt_publish_model *model = [Device_mqtt_publish_model mj_objectWithKeyValues:data];
        if (![model.dev_id isEqualToString:self.deviceInfo.data.device_id]) {
//            DLog(@"mqtt消息与当前deviceId不一致 %@ %@", model.dev_id, self.deviceInfo.data.device_id);
            return;
        }
        if ([topic isEqualToString:@"ainankang_dev"]) {
            // 设备的 {"dev_id":"IF-YA-HBB-19A-C44F3314ECF5-6300","dev_type":"YA-HBB-19A","cmd":"login_report","data":[{"reg":"MAC","value":"C4-4F-33-14-EC-F5"},{"reg":"IP","value":"192.168.1.14"}]}
            
            
            if ([model.cmd isEqualToString:@"login_report"]) {
                if (!self.login_report_MAC) {
                    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    DLog(@"data:%@ topic:%@", str, topic);
                    for (NSDictionary *dic in model.data) {
                        NSString *reg = [dic objectForKey:@"reg"];
                        if ([reg isEqualToString:@"MAC"]) {
                            NSString *value = [dic objectForKey:@"value"];
                            self.login_report_MAC = value;
                            self.login_report_dev_type = model.dev_type;
                            [self send_handshake_msg];
                        }
                        
                    }
                    
                }
            }else if ([model.cmd isEqualToString:@"handshake_res"]) {
                // topic:ainankang_dev {"dev_id":"IF-YA-HBB-19A-C44F3314ECF5-6300","data":[{"reg":"handshake","value":0}],"dev_type":"YA-HBB-19A","cmd":"handshake_res","index":"1","index":0}
                NSDictionary *handshake = model.data.firstObject;
                if ([[handshake objectForKey:@"reg"] isEqualToString:@"handshake"]) {
                    NSNumber *value = [handshake objectForKey:@"value"];
                    if (value.integerValue == 0) {
                        DLog(@"1----------->握手成功 ");
                        self.handshake_yes = YES;
                        
                        
                    }
                }
            }
            
            
        }else if([topic isEqualToString:self.ainankang_dev_topic]){
            // 握手后，设备 主题
            
            if(![model.cmd isEqualToString:@"weighing_get_active"] && ![model.cmd isEqualToString:@"sensor_data"]){
                NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                DLog(@"屏蔽了sensor_data和weighing_get_active。\n data:%@ topic:%@", str, topic);
            }

            
            Device_mqtt_publish_model *model = [Device_mqtt_publish_model mj_objectWithKeyValues:data];
            
            if ([model.cmd isEqualToString:@"dev_execute"] || [model.cmd isEqualToString:@"dev"]) {
                
                for (NSDictionary *dict in model.data) {
                    [self handle_dev_execute_reg_dict:dict];
                }
                
            }else if ([model.cmd isEqualToString:@"dev_active"]) {
                
                for (NSDictionary *dict in model.data) {
                    [self handle_dev_execute_reg_dict:dict];
                }
                
            }else if([model.cmd isEqualToString:@"handshake_res"]){
                // "value": 0/1~255   succeed/failed。示例  {"reg":"handshake","value":0}
                NSDictionary *handshake = model.data.firstObject;
                if ([[handshake objectForKey:@"reg"] isEqualToString:@"handshake"]) {
                    NSNumber *value = [handshake objectForKey:@"value"];
                    if (value.integerValue == 0) {
                        DLog(@"1----------->握手成功 ");
                        self.handshake_yes = YES;
                        

                    }
                }
            }else if([model.cmd isEqualToString:@"audio_execute"]){
                // audio_execute
                for (NSDictionary *dict in model.data) {
                    [self handle_audio_execute_reg_dict:dict];
                }
            }else if([model.cmd isEqualToString:@"audio"]){
                // audio
                for (NSDictionary *dict in model.data) {
                    [self handle_audio_execute_reg_dict:dict];
                }
            }else if([model.cmd isEqualToString:@"audio_active"]){
                // audio_active
                for (NSDictionary *dict in model.data) {
                    [self handle_audio_active_reg_dict:dict];
                }
            }else if([model.cmd isEqualToString:@"off_line"]){
                // off_line {"dev_id":"IF-YA-HBB-19A-C44F3314ECF5-6300","dev_type":"YA-HBB-19A","cmd":"off_line","data":[{"reg":"time","value":"2020-03-19 13:35:41"}]}
                
                NSDictionary *dict = model.data.firstObject;
                NSString *reg = [dict objectForKey:@"reg"];
                NSString *value = [dict objectForKey:@"value"];
                if ([reg isEqualToString:@"time"] && ![Anktool strIsBlank:value]) {
                    
                    
                    
                    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init ];
                    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    NSDate * d1 = [dateFormatter dateFromString:value];
                    
                    
                    
                    NSTimeZone * zone = [NSTimeZone systemTimeZone];
                    
                    // 将偏差的时间加到原来的时间上就是正式的时间
                    d1 = [d1 dateByAddingTimeInterval:[zone secondsFromGMTForDate:d1]];
                    
                    
                    
                    
                    
                    
                    NSDate * d3 =  [NSDate dateWithTimeIntervalSinceNow:8 * 60 * 60];
                    
                    NSTimeInterval t2 = [d3 timeIntervalSinceDate:d1];
                    
                    if (t2 > 120) {// 超过120s的遗嘱消息，不处理
                        DLog(@"超过120s的遗嘱消息，不处理");
                        return;
                    }
                    
                    //[MBProgressHUD showTipMessageInView:[NSString stringWithFormat:@"%@设备掉线", value]];
                    self.handshake_yes = NO;
                    
                    // 摇摆停止状态
                    [self.yaobaiVc change_status_timeBtn:self.yaobaiVc.timeBtns[0]];
//                    [self.yaobaiVc.startBtn setSelected:NO];
//                    [self.yaobaiVc.stopBtn setSelected:YES];
                    self.yaobaiVc.startBtn.selected = self.yaobaiVc.stopBtn.selected = NO;

                    [self.yaobaiVc.coutDownBtn stopCountDown]; //** Or you can use [timer3 setCountDownToDate:aDate];
                    
                    // 音乐播放停止状态
                    self.audio_execute_status = @"close";
                    //                open/close/pause/recover/mute
                    self.musicVc.play_pause_btn.selected = NO;
                    self.currentSong = self.currentSong;
                    
                    // 重置状态
                    self.login_report_MAC = self.login_report_dev_type = nil;
                    self.has_send_music_list = NO;
                }
                
            }else if([model.cmd isEqualToString:@"weighing_get_active"]){
                // {"dev_id":"IF-YA-HBB-19A-C44F3314ECF5-6300","dev_type":"YA-HBB-19A","cmd":"weighing_get_active","index":0,"data":[{"reg":"weight","value":2147483647},{"reg":"gap","value":0}]}
                //            for (NSDictionary *dict in model.data) {
                //                [self handle_audio_active_reg_dict:dict];
                //            }
//                DLog(@"有连接");
                self.handshake_yes = YES;

                
            }else if([model.cmd isEqualToString:@"sensor_data"]){
                
                for (NSDictionary *dict in model.data) {
                    NSString *reg = dict[@"reg"];
                    NSUInteger value = [dict[@"value"] integerValue];
                    if ([reg isEqualToString:@"TEM_ENV"]) {
                        self.guanaiVc.huanjing_wendu_lb.text = [Anktool wendu:value];
                    }else if ([reg isEqualToString:@"TEM_QUILT1"]){
                        //                    self.guanaiVc.beigan_wendu_lb.text = [NSString stringWithFormat:@"%lu℃", (unsigned long)value];
                    }else if ([reg isEqualToString:@"TEM_QUILT2"]){
                        self.guanaiVc.beigan_wendu_lb.text = [Anktool wendu:value];
                        
                    }else if ([reg isEqualToString:@"TEM_IN"]){}else if ([reg isEqualToString:@"RT_NS"]){}
                }
            }else if ([model.cmd isEqualToString:@"login_report"]){
                self.handshake_yes = YES;
                

            }
        }else{}// 除约定外的其他主题
        
    });
}

- (void)handle_dev_execute_reg_dict:(NSDictionary *)dict{
    NSString *reg = [dict objectForKey:@"reg"];
    NSString *value = [dict objectForKey:@"value"];
    if ([reg isEqualToString:@"lights_sw"] || [reg isEqualToString:@"lights_sw_get"]) {
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            if ([value isEqualToString:@"close"]) {
                
                self.musicVc.light_switch.on = self.yaobaiVc.light_switch.on = NO;
                
            }else if ([value isEqualToString:@"open"]) {
                self.musicVc.light_switch.on = self.yaobaiVc.light_switch.on = YES;
            }
            
        });
        
    }else if ([reg isEqualToString:@"time"] || [reg isEqualToString:@"time_get"] ) {
        // 处理时间参数，相减得到是倒计时多少分钟，如果是0就是停止状态，时间默认15分钟；如果大于零，显示对应的时间段；
        // 当前时间减去末位时间，就是还剩，差如果大于 设定时间段，说明倒计时完了，小于倒计时段，就用 前-末 - 时间段，得出剩余倒计时间
        
        //        [self.yaobaiVc change_status_timeBtn:self.yaobaiVc.timeBtns[value.integerValue-1]];
        if (![Anktool strIsBlank:value]) {
            NSArray *arr = [value componentsSeparatedByString:@"/"];
            if (arr.count == 2) {
                
                if ([arr.firstObject isEqualToString:arr.lastObject]) {
                    // 停止状态
                    self.yaobaiVc.counting = NO;
                    
                    for (UIButton *b in self.yaobaiVc.timeBtns) {
                        if (b.isSelected) {
                            [self.yaobaiVc change_status_timeBtn:b];
                            break;
                        }
                    }
                    
//                    [self.yaobaiVc.startBtn setSelected:NO];
//                    [self.yaobaiVc.stopBtn setSelected:YES];
                    self.yaobaiVc.startBtn.selected = self.yaobaiVc.stopBtn.selected = NO;
                }else{
                    
                    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init ];
                    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    NSDate * d1 = [dateFormatter dateFromString:arr.firstObject];
                    NSDate * d2 = [dateFormatter dateFromString:arr.lastObject];
                    
                    
                    NSTimeZone * zone = [NSTimeZone systemTimeZone];
                    
                    // 将偏差的时间加到原来的时间上就是正式的时间
                    d1 = [d1 dateByAddingTimeInterval:[zone secondsFromGMTForDate:d1]];
                    
                    d2 = [d2 dateByAddingTimeInterval:[zone secondsFromGMTForDate:d2]];
                    
                    
                    NSTimeInterval t1 = [d2 timeIntervalSinceDate:d1];
                    
                    NSDate * d3 =  [NSDate dateWithTimeIntervalSinceNow:8 * 60 * 60];
                    
                    NSTimeInterval t2 = [d3 timeIntervalSinceDate:d1];
                    
//                    DLog(@"设定时间间隔%f 已经过了的时间%f", t1, t2);
                    
                    
                    if ( t1 > t2 ){
                        
                        for (UIButton *btn in self.yaobaiVc.timeBtns) {
                            if ([btn.currentTitle containsString:@(t1 / 60).stringValue]) {
                                
                                [self.yaobaiVc change_status_timeBtn:btn];
                                break;
                            }
                        }
                        self.yaobaiVc.totalInterval = t1;
                        NSInteger time = t1 - t2;
//                        self.yaobaiVc.coutDownBtn.userInfo = @(time); //** Or you can use [timer3 setCountDownToDate:aDate];
                        [self.yaobaiVc.coutDownBtn startCountDownWithSecond:time];
                        self.yaobaiVc.counting = YES;
//                        [self.yaobaiVc.startBtn setSelected:YES];
//                        [self.yaobaiVc.stopBtn setSelected:NO];
                        self.yaobaiVc.startBtn.selected = self.yaobaiVc.stopBtn.selected = YES;

                    }else{
                        // 停止状态
                        self.yaobaiVc.counting = NO;
                        [self.yaobaiVc change_status_timeBtn:self.yaobaiVc.timeBtns.firstObject];
//                        [self.yaobaiVc.startBtn setSelected:NO];
//                        [self.yaobaiVc.stopBtn setSelected:YES];
                        self.yaobaiVc.startBtn.selected = self.yaobaiVc.stopBtn.selected = NO;

                        //                        [self.yaobaiVc.countDownLb setCountDownTime:0.1]; //** Or you can use [timer3 setCountDownToDate:aDate];
                        
                    }
                }
                
                
            }else{
                // 停止状态
                self.yaobaiVc.counting = NO;
                [self.yaobaiVc change_status_timeBtn:self.yaobaiVc.timeBtns[0]];
//                [self.yaobaiVc.startBtn setSelected:NO];
//                [self.yaobaiVc.stopBtn setSelected:YES];
                self.yaobaiVc.startBtn.selected = self.yaobaiVc.stopBtn.selected = NO;

            }
        }
        
    }
    
    else if ([reg isEqualToString:@"range_level"] || [reg isEqualToString:@"range_level_get"]) {
        //默认 {"dev_id":"IF-YA-HBB-19A-C44F3314ECF5-6300","dev_type":"YA-HBB-19A","cmd":"dev_execute","index":0,"data":[{"reg":"range_level_get","value":0},{"reg":"time_get","value":"/"},{"reg":"lights_sw_get","value":"close"}]} topic:ainankang_dev/IF-YA-HBB-19A-C44F3314ECF5-6300 retained:0
        int index = ABS(value.intValue);
        if (index == 0) {
            index = 1;
        }
        [self.yaobaiVc change_status_speedBtn:self.yaobaiVc.speedBtns[index-1]];
        
    }
}

// 处理音乐相关
- (void)handle_audio_active_reg_dict:(NSDictionary *)dict{
    NSString *reg = [dict objectForKey:@"reg"];
    NSString *value = [dict objectForKey:@"value"];
    [self music_reg:reg value:value];
}

- (void)handle_audio_execute_reg_dict:(NSDictionary *)dict{
    NSString *reg = [dict objectForKey:@"reg"];
    NSString *value = [dict objectForKey:@"value"];
    [self music_reg:reg value:value];
    
}

- (void)music_reg:(NSString *)reg value:(NSString *)value{
    if ([reg isEqualToString:@"volume"] || [reg isEqualToString:@"volume_get"] ) {
        
        self.musicVc.volume_slider.value = value.integerValue;
    }else if ( [reg isEqualToString:@"broadcast_pace"]) {}else if ([reg isEqualToString:@"addr"]) {}else if ([reg isEqualToString:@"url"] || [reg isEqualToString:@"url_get"]) {
        if ([Anktool strIsBlank:value]) {
            self.currentSong = self.defaultSong;
        }else{
            // 发送
            
            for (NSString *key in self.music_database.allKeys) {
                GetMusicData *aData = [self.music_database objectForKey:key];
                for (GetMusicList *aSong in aData.list) {
                    if ([aSong.url isEqualToString:value]) {
                        self.currentSong = aSong;
                        
                        self.currentListData = aData;
                        
                        return;
                    }
                }
            }
            
            
            if (!self.currentSong) {// 匹配不到，就默认第一首
                self.currentSong = self.defaultSong;
            }
        }
    
    }else if ([reg isEqualToString:@"status"] || [reg isEqualToString:@"status_get"]) {
        
        self.audio_execute_status = value;
        //                open/close/pause/recover/mute
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            if ([value isEqualToString:@"open"]) {
                self.musicVc.play_pause_btn.selected = YES;
            }else if ([value isEqualToString:@"close"]) {
                self.musicVc.play_pause_btn.selected = NO;
            }else if ([value isEqualToString:@"pause"]) {
                self.musicVc.play_pause_btn.selected = NO;
            }else if ([value isEqualToString:@"recover"]) {
                self.musicVc.play_pause_btn.selected = YES;
            }
            
            self.currentSong = self.currentSong;
        });
        
        
    }else if ([reg isEqualToString:@"mode"] || [reg isEqualToString:@"mode_get"]) {
        // 播放模式：单曲播放/单曲循环/列表循环/列表随机播放（single/single_cycle/lists_cycle/random）2020.3.16 lzy 只用到后三个
        
        self.audio_play_model = value;
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            if ([value isEqualToString:@"single_cycle"]) {
                [self.musicVc.play_mode_btn setImage:[UIImage imageNamed:value] forState:UIControlStateNormal];
            }else if ([value isEqualToString:@"lists_cycle"]) {
                [self.musicVc.play_mode_btn setImage:[UIImage imageNamed:value] forState:UIControlStateNormal];
            }else if ([value isEqualToString:@"random"]) {
                [self.musicVc.play_mode_btn setImage:[UIImage imageNamed:value] forState:UIControlStateNormal];
            }else if ([value isEqualToString:@"single"]) {
                
            }
            
        });
    }else if ([reg isEqualToString:@"music_list"] || [reg isEqualToString:@"music_list_get"] ) {
        self.handshake_yes = YES;

        DLog(@"3------------>询问音乐列表 结果%@", value);
        if (value.integerValue > 0) {
            DLog(@"4------------> 设备有播放列表，询问音乐播放情况");
            [self query_music_info];
            self.has_send_music_list = YES;
        }else{
            if (self.has_send_music_list) {
                DLog(@"3------------>设备无音乐列表，app下发过了，不再下发");

                return;
            }else{
                DLog(@"4------------------>设备无音乐列表,app下发");
                self.has_send_music_list = YES;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{// 这一秒延时非常重要，嵌入式那边猜测可能是下发音乐列表时，设备又在执行 查询设备本地列表是否存在，造成的资源竞争，设备就不断直接重启的bug。
                    [self send_music_list_reg];
                });
                
            }
    
        }
    }
}

- (void)sessionManager:(MQTTSessionManager *)sessionManager didChangeState:(MQTTSessionManagerState)newState{
    NSString *str;
    switch (newState) {
        case MQTTSessionManagerStateStarting:
            str = @"正在启动";
            break;
            
        case MQTTSessionManagerStateConnecting:
            str = @"正在连接";
            break;
        case MQTTSessionManagerStateError:
            str = @"发生错误";
            break;
        case MQTTSessionManagerStateConnected:
            str = @"连接成功";
            break;
        case MQTTSessionManagerStateClosing:
            str = @"正在关闭";
            break;
        case MQTTSessionManagerStateClosed:
            str = @"已经关闭";
            break;
    }
    DLog(@"%@", str);
}
#pragma mark - ================== 懒加载 ==================
- (NSString *)audio_play_model{
    if(_audio_play_model == nil) _audio_play_model = @"lists_cycle";
    return _audio_play_model;
}
- (DeviceMusicVc *)musicVc{
    if(_musicVc == nil) _musicVc = [[DeviceMusicVc alloc] init];
    return _musicVc;
}
- (DeviceYaobaiVc *)yaobaiVc{
    if(_yaobaiVc == nil) _yaobaiVc = [[DeviceYaobaiVc alloc] init];
    return _yaobaiVc;
}
- (DeviceGuanaiVc *)guanaiVc{
    if(_guanaiVc == nil) _guanaiVc = [[DeviceGuanaiVc alloc] init];
    return _guanaiVc;
}
- (void)check_handshake{
    self.check_handshake_timer =  [NSTimer timerWithTimeInterval:25 repeats:NO block:^(NSTimer * _Nonnull timer) {
        if (!self.handshake_yes) {
            [self shebei_offline_popView];
        }
    }];
    [[NSRunLoop currentRunLoop] addTimer:self.check_handshake_timer forMode:NSDefaultRunLoopMode];

}
- (void)shebei_offline_popView{
    __weak __typeof(self) weakSelf = self;
    MMPopupCompletionBlock btnBlock = ^(MMPopupView *popupView, BOOL finished){
        
        DLog(@"%d", finished);
        if (finished && !weakSelf.handshake_yes) {
            if (self.login_report_MAC.length > 0) {
                [weakSelf send_handshake_msg];
            }
        }
    };
    
    Shebei_offline_popView *pinView = [Shebei_offline_popView new];
    pinView.img_name = @"kz_failed_icon";
    pinView.tipStr = @"未连接到设备，请重试";
    pinView.queren_btn_title_str = @"重试";
    pinView.btnBlock = btnBlock;
    [pinView show];
}
- (Music_page_list_vc *)music_list_vc{
    if(_music_list_vc == nil)
    {
        _music_list_vc = [[Music_page_list_vc alloc] init];
        
        if (self.currentSong) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"current_song_change_to_list_vc" object:nil userInfo:@{@"current_song_change_to_list_vc" : self.currentSong}];
                
            });
        }
       
    }
    
    return _music_list_vc;
}
- (void)show_musiclist{
    
    [self presentPanModal:self.music_list_vc];
    
    
    
}
/*
- (void)show_musiclist{

    [self presentPanModal:self.music_list_vc];
    
    return;
    __weak __typeof(self) weakSelf = self;
    MMPopupCompletionBlock btnBlock = ^(MMPopupView *popupView, BOOL finished){};
    
    Ank_musicList_view *pinView = [Ank_musicList_view new];
    pinView.dataArr = self.musicList.data.music_list;
//    pinView.currentIndex = [self.musicList.data.music_list indexOfObject:self.currentSong];
    pinView.selectedRowBlk = ^(App_getMusicListMusic_list *currentSong) {
        
        if (![Anktool strIsBlank:currentSong.file_name]) {
            
            if ([currentSong.url isEqualToString:self.currentSong.url]) {
                NSArray *dataArr = nil;
               if ([self.audio_execute_status isEqualToString:@"open"]) {
                    // 当前是在播放音乐的状态，再点击一下是暂停
                    dataArr =@[ @{@"reg": @"status", @"value" : @"pause"}];
                    
                    self.audio_execute_status = @"pause";
                    
                }else if ([self.audio_execute_status isEqualToString:@"close"]) {
                    
                    // 当前是没有在播放音乐的状态，再点击一下是播放第一首歌曲
                    dataArr =@[ @{@"reg": @"status", @"value" : @"open"}];
                    self.audio_execute_status = @"open";
                    
                }else if ([self.audio_execute_status isEqualToString:@"pause"]) {
                    // 当前是在播放音乐的，只是音乐处于暂停状态，再点击一下是恢复
                    dataArr =@[ @{@"reg": @"status", @"value" : @"recover"}];
                    self.audio_execute_status = @"recover";
                    
                }else if ([self.audio_execute_status isEqualToString:@"recover"]) {
                    // 当前是音乐恢复播放的状态，再点击一下是暂停
                    dataArr =@[ @{@"reg": @"status", @"value" : @"pause"}];
                    self.audio_execute_status = @"pause";
                    
                }
//                else if ([self.audio_execute_status isEqualToString:@"mute"]){}
                
                [self queryWith_cmd:@"audio" data:dataArr];
                
                }else{
                
                NSMutableArray *dataArr = [NSMutableArray array];
                [dataArr addObject:@{
                                     @"reg" : @"url" // 当前播放的 音频文件路径/URL地址
                                     , @"value" : currentSong.url
                                     }];
                [dataArr addObject:@{
                                     @"reg" : @"status"
                                     , @"value" : @"open"
                                     }];
                
                [weakSelf queryWith_cmd:@"audio" data:dataArr];
            }
        }
        
        
        
    };
    [pinView showWithBlock:btnBlock];
    
}
 */
- (void)setCurrentSong:(GetMusicList *)currentSong{
    if ([currentSong.url isEqualToString:_currentSong.url]) {
        return;
    }
    _currentSong = currentSong;
    self.musicVc.songNameLb.text = self.currentSong.title;
    self.musicVc.songAuthorLb.text = self.currentSong.author;

    if (currentSong != nil) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"current_song_change_to_list_vc" object:nil userInfo:@{@"current_song_change_to_list_vc" : currentSong}];

    }
    
}
#pragma mark - ================== 缓存歌曲的请求 ==================
- (void)cache_music{
    
    GetMusicReq *api =[[GetMusicReq alloc] init];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *oneReq) {
        // 你可以直接在这里使用 self
        NSLog(@"succeed");
        
        MusicCategory *musicCategory = [MusicCategory mj_objectWithKeyValues:oneReq.responseJSONObject];
        self.musicCategory = musicCategory;
        
        for (MusicCategoryData *ac in musicCategory.data) {
            GetMusic_category_list *req = [[GetMusic_category_list alloc] init_page:@"1" page_size:@"100" category_id:@(ac.ID).stringValue];
            
            [req startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull twoReq) {
                GetMusic_category_list *theRequest = (GetMusic_category_list *)twoReq;
                NSDictionary *response = twoReq.responseJSONObject;
                NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
                if ([error_code isEqualToString:@"0"]) {
                    GetMusic *model = [GetMusic mj_objectWithKeyValues:response];
                    
                    if (!model.data.list || model.data.list.count == 0) {
                        DLog();
                        return;
                    }else{
                        [self.music_database setObject:model.data forKey:theRequest.category_id];
                    }
                    
                }
            } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                
            }];
            
        }
        
        
    } failure:^(YTKBaseRequest *request) {
        // 你可以直接在这里使用 self
        NSLog(@"failed");
    }];
}
@end
